package com.icloud.system.boot.controller.admin;

import com.icloud.auth.api.vo.Oauth2TokenVo;
import com.icloud.common.core.api.CommonResult;
import com.icloud.common.core.api.ResultCode;
import com.icloud.common.web.annotation.AdminOperationLog;
import com.icloud.common.web.annotation.AdminWhiteListOperationLog;
import com.icloud.common.web.exception.Asserts;
import com.icloud.common.web.util.AuthUtil;
import com.icloud.system.boot.dto.LoginDto;
import com.icloud.system.boot.dto.UpdatePasswordDto;
import com.icloud.system.boot.service.AdminUserAuthService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@Api(tags = "后台认证服务")
@RequestMapping("/admin/auth")
@RequiredArgsConstructor
public class AdminUserAuthController {
    private final AdminUserAuthService adminUserAuthService;
    private final AuthUtil authUtil;

    @ApiOperation(value = "后台账号登录")
    @AdminWhiteListOperationLog("后台账号登录")
    @PostMapping(value = "/login")
    @ResponseBody
    public CommonResult<Oauth2TokenVo> login(@Validated @RequestBody LoginDto dto) {
        return adminUserAuthService.adminUserLogin(dto.getUsername(), dto.getPassword());
    }

    @ApiOperation(value = "后台账号登出")
    @AdminOperationLog("后台账号登出")
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<Boolean> logout() {
        return adminUserAuthService.adminUserLogout();
    }

    @AdminOperationLog("修改密码")
    @ApiOperation("修改密码")
    @PutMapping(value = "/update/password")
    public CommonResult<Void> resetPassword(@Validated @RequestBody UpdatePasswordDto dto) {
        //验证两次输入的密码是否一致
        Asserts.fail(! dto.getPassword().equals(dto.getConfirmPassword()), ResultCode.PASSWORD_ENTERED_TWICE_NOT_MATCH);
        adminUserAuthService.updatePasswordById(authUtil.getUserId(), dto.getPassword());
        return CommonResult.success();
    }
}
